#pragma once
#include "tcpserver.hpp"
#include "httpprotcol.hpp"
#include "Socket.hpp"

using namespace TcpServerModule;
using namespace SocketModule;

namespace HttpSeverModule
{
    using http_handler_t = std::function<void(HttpRequest &, HttpResponse &)>;
    class HttpSever
    {
    public:
        HttpSever(int port)
            : _tsvr(std::make_unique<TcpServer>(port))
        {
        }
        void Register(std::string funcname, http_handler_t func)
        {
            _route[funcname] = func;
        }
        bool SafeCheck(const std::string &service) // 检查服务是否存在
        {
            auto iter = _route.find(service);
            return iter != _route.end();
        }
        void Start()
        {
            _tsvr->InitServer([this](SockPtr sockp, InetAddr client)
                              { this->HandlerHttpRequest(sockp, client); });
            _tsvr->Start();
        }
        bool HandlerHttpRequest(SockPtr sockp, InetAddr client)
        {
            std::string req_str;
            while (true)
            {
                int n = sockp->Recv(req_str);
                if (n > 0)
                {
                    LOG(DEBUG)<<"收到信息："<<req_str;
                    HttpRequest hrq;
                    hrq.Deserialize(req_str);
                    HttpResponse hrp;
                    if (hrq.HasArgs())
                    {
                        std::string service = hrq.Path();
                        if (SafeCheck(service))
                            _route[service](hrq, hrp); // 功能调用
                        else
                            hrp.Build(hrq); // debug
                    }
                    else
                    {
                        hrp.Build(hrq);
                    }
                    std::string resp_str;
                    hrp.Serialize(resp_str);
                    sockp->Send(resp_str);
                    //return true;
                }
                else if (n == 0)
                {
                    LOG(INFO) << "client quit,client: " << client.Ip();
                    break;
                }
                else
                {
                    LOG(ERROR) << "recv fail";
                    return false;
                }
            }
            return true;
        }

    private:
        std::unique_ptr<TcpServer> _tsvr;
        std::unordered_map<std::string, http_handler_t> _route; // 功能路由
    };
}